package com.haitaoit.chengquan.module.center.activity.info;

import android.content.Intent;
import android.os.Bundle;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.style.RelativeSizeSpan;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TextView;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.haitaoit.chengquan.R;
import com.haitaoit.chengquan.base.BaseActivity;
import com.haitaoit.chengquan.module.center.adapter.MyPointAdapter;
import com.haitaoit.chengquan.module.center.model.MyPointModel;
import com.haitaoit.chengquan.module.center.model.UserInfoModel;
import com.haitaoit.chengquan.utils.Constant;
import com.haitaoit.chengquan.utils.DateTimeUtil;
import com.haitaoit.chengquan.utils.GetSign;
import com.haitaoit.chengquan.utils.HttpUtilsSingle;
import com.haitaoit.chengquan.utils.NameValuePairSign;
import com.haitaoit.chengquan.utils.PreferenceUtils;
import com.haitaoit.chengquan.utils.ToastUtils;
import com.haitaoit.chengquan.view.MyListView;
import com.haitaoit.chengquan.view.PullToRefreshBase;
import com.haitaoit.chengquan.view.PullToRefreshScrollView;
import com.lidroid.xutils.ViewUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.view.annotation.ViewInject;
import com.lidroid.xutils.view.annotation.event.OnClick;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

public class MyPointActivity extends BaseActivity implements PullToRefreshBase.OnRefreshListener<ScrollView> {
    @ViewInject(R.id.pullrefreshscrollview)
    PullToRefreshScrollView pullrefreshscrollview;

    private ScrollView mScrollView;
    private LinearLayout null_information_layout;
    private MyListView listView;

    private boolean isFrist = true;
    private int page = 1;

    private MyPointAdapter adapter;
    private TextView point_num;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView_V(R.layout.pullrefreshscollview);
        setTitle_V("我的积分");
        setLeftShow(1, R.mipmap.left);
        setRightShow(0, R.string.point_rule);
        backLeft_V();
        ViewUtils.inject(this);


        View view = LayoutInflater.from(this).inflate(R.layout.activity_my_point, null);
        null_information_layout = (LinearLayout) view.findViewById(R.id.null_information_layout);
        listView = (MyListView) view.findViewById(R.id.scrollview_listview);
        point_num = (TextView) view.findViewById(R.id.point_num);
        // 部分字体变大变色
        SpannableString msp = new SpannableString(UserInfoModel.getUser_info().getIntegral() + " 积分");
        msp.setSpan(new RelativeSizeSpan(2f), 0, UserInfoModel.getUser_info().getIntegral().length(),
                Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        point_num.setText(msp);

        // 兑换余额
        view.findViewById(R.id.point_change).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivityForResult(new Intent(MyPointActivity.this, MyPointChangeActivity.class), 222);
            }
        });

        pullrefreshscrollview.setPullLoadEnabled(true);
        pullrefreshscrollview.setPullRefreshEnabled(false);
        pullrefreshscrollview.setOnRefreshListener(this);
        pullrefreshscrollview.setLastUpdatedLabel(DateTimeUtil
                .getFormatDateTime(DateTimeUtil.getCurrTimestamp()));
        mScrollView = pullrefreshscrollview.getRefreshableView();
        mScrollView.setFillViewport(true);
        mScrollView.setVerticalScrollBarEnabled(false);
        mScrollView.addView(view);

        adapter = new MyPointAdapter(this);
        listView.setAdapter(adapter);
        httpGetuser_integral_records_list();
    }

    @OnClick({R.id.right,})
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.right:
                startActivity(new Intent(MyPointActivity.this, MyPointRuleActivity.class));
                break;
        }
        super.onClick(v);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == 222 && resultCode == 1) {
            httpGetUserInfo();
        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    private void httpGetUserInfo() {
        List<NameValuePairSign> list = new ArrayList<NameValuePairSign>();
        list.add(new NameValuePairSign("user_id", PreferenceUtils.getPrefString("user_id", "")));
        String sign = GetSign.genPackageSign(list);

        RequestParams params = new RequestParams();
        params.addQueryStringParameter("user_id", PreferenceUtils.getPrefString("user_id", ""));
        params.addQueryStringParameter("sign", sign);

        HttpUtilsSingle.doGet(this, false, Constant.GetUser_model, params, new RequestCallBack<String>() {
            @Override
            public void onSuccess(ResponseInfo<String> arg0) {
                String jsonString = arg0.result.toString();
                JSONObject json;
                try {
                    json = new JSONObject(jsonString);
                    String Errcode = json.getString("ErrCode");
                    String Errmsg = json.getString("ErrMsg");
                    String Response = json.getString("Response");
                    Gson gson = new Gson();
                    switch (Integer.valueOf(Errcode)) {
                        case 1:// 失败
                            ToastUtils.showToast(Errmsg);
                            return;
                        case 0:// 成功
                            UserInfoModel user_info = gson.fromJson(Response, UserInfoModel.class);
                            UserInfoModel.setUser_info(user_info);

                            // 部分字体变大变色
                            SpannableString msp = new SpannableString(UserInfoModel.getUser_info().getIntegral() + " 积分");
                            msp.setSpan(new RelativeSizeSpan(2f), 0, UserInfoModel.getUser_info().getIntegral().length(),
                                    Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
                            point_num.setText(msp);

                            isFrist = true;
                            page = 1;
                            httpGetuser_integral_records_list();
                            return;
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            public void onFailure(HttpException arg0, String arg1) {
                ToastUtils.showToast("获取数据失败,请检查网络");
            }
        });
    }

    private void httpGetuser_integral_records_list() {
        List<NameValuePairSign> list = new ArrayList<NameValuePairSign>();
        list.add(new NameValuePairSign("user_id", PreferenceUtils.getPrefString("user_id", "")));
        list.add(new NameValuePairSign("page", page + ""));
        list.add(new NameValuePairSign("pagesize", Constant.PageSize));
        String sign = GetSign.genPackageSign(list);

        RequestParams params = new RequestParams();
        params.addQueryStringParameter("user_id", PreferenceUtils.getPrefString("user_id", ""));
        params.addQueryStringParameter("page", page + "");
        params.addQueryStringParameter("pagesize", Constant.PageSize);
        params.addQueryStringParameter("sign", sign);

        HttpUtilsSingle.doGet(this, false, Constant.Getuser_integral_records_list, params, new RequestCallBack<String>() {
            @Override
            public void onSuccess(ResponseInfo<String> arg0) {
                String result = arg0.result.toString();
                List<MyPointModel> new_list = new ArrayList<MyPointModel>();
                try {
                    JSONObject json = new JSONObject(result);
                    String Errcode = json.getString("ErrCode");
                    String Errmsg = json.getString("ErrMsg");
                    String Response = json.getString("Response");
                    Gson gson = new Gson();
                    switch (Integer.valueOf(Errcode)) {
                        case 1:// 失败
                            ToastUtils.showToast(Errmsg);
                            pullrefreshscrollview.onPullDownRefreshComplete();
                            pullrefreshscrollview.onPullUpRefreshComplete();
                            new_list = new ArrayList<MyPointModel>();
                            break;
                        case 0:// 成功
                            new_list = gson.fromJson(Response,
                                    new TypeToken<List<MyPointModel>>() {
                                    }.getType());
                            break;
                        case 2:// 暂无内容
                            pullrefreshscrollview.onPullDownRefreshComplete();
                            pullrefreshscrollview.onPullUpRefreshComplete();
                            new_list = new ArrayList<MyPointModel>();
                            break;
                    }
                    if (isFrist) {
                        if (isNullDate(new_list)) {
                            adapter.setList(new_list);
                            adapter.notifyDataSetChanged();
                        }
                        pullrefreshscrollview.onPullDownRefreshComplete();
                    } else {
                        List<MyPointModel> allList = adapter.getList();
                        allList.addAll(new_list);
                        adapter.setList(allList);
                        adapter.notifyDataSetChanged();
                        pullrefreshscrollview.onPullUpRefreshComplete();
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailure(HttpException arg0, String arg1) {
                ToastUtils.showToast("获取数据失败,请检查网络");
            }
        });
    }

    /**
     * @tab 判断listview是否有值
     */
    private boolean isNullDate(List<MyPointModel> rewordList) {
        if (rewordList == null || rewordList.size() == 0) {
            null_information_layout.setVisibility(View.VISIBLE);
            listView.setVisibility(View.GONE);
            return false;
        } else {
            null_information_layout.setVisibility(View.GONE);
            listView.setVisibility(View.VISIBLE);
            return true;
        }
    }

    @Override
    public void onPullDownToRefresh(PullToRefreshBase<ScrollView> refreshView) {
        pullrefreshscrollview.setLastUpdatedLabel(DateTimeUtil
                .getFormatDateTime(DateTimeUtil.getCurrTimestamp()));
        isFrist = true;
        page = 1;
        httpGetuser_integral_records_list();
    }

    @Override
    public void onPullUpToRefresh(PullToRefreshBase<ScrollView> refreshView) {
        pullrefreshscrollview.setLastUpdatedLabel(DateTimeUtil
                .getFormatDateTime(DateTimeUtil.getCurrTimestamp()));
        isFrist = false;
        page++;
        httpGetuser_integral_records_list();
    }
}
